package com.nowcoder.community.controller.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;

/**
 * 将model内的cookies字段的cookies设置到response cookie.
 */
@Component
public class ModelCookieInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(request.getServletPath());
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView){
        if (modelAndView != null) {
//            Object cookie = modelAndView.getModel().get("cookie");
//            if (cookie instanceof Cookie) {
//                response.addCookie((Cookie) cookie);
//            }
            Object cookies = modelAndView.getModel().get("cookies");
            if (cookies instanceof Collection) {
                for (Object c : (Collection<?>) cookies) {
                    if (c instanceof Cookie) {
                        response.addCookie((Cookie) c);
                    }
                }
            }
        }
    }
}
